<template>
  <div>
    <el-row>
      <el-tabs type="border-card">
        <el-tab-pane label="重要性度量">
          <div class="btn">
            <div class="tips" v-if="this.dataset != ''">
              当前选择的数据集: {{ dataset }}
            </div>
            <div
              class="tips"
              style="font-size: 15px; margin-top: 10px"
              v-if="this.dataset == ''"
            >
              未选择数据集，请前往风险溯源进行前置操作
            </div>
            <el-button
              type="primary"
              :disabled="startFlag"
              :loading="startFlag"
              style="width: 100px"
              @click="start"
              >开始</el-button
            >
          </div>
          <div>
            <div class="table" v-if="completedFlag">
              <el-table
                :data="tableData"
                :header-cell-style="{ background: 'rgba(242, 242, 242, 0.65)' }"
                border
                height="350"
                :row-style="{ height: '28px' }"
                :cell-style="{ padding: '0px' }"
                header-row-class-name="active_header"
                header-cell-class-name="active_header"
                cell-class-name="content_center"
                style="width: 98%"
              >
                <el-table-column
                  v-for="(val, key) in tableLabel"
                  :prop="key"
                  :label="val"
                  :key="key"
                  sortable
                />
              </el-table>
            </div>
            <el-card style="margin-top: 10px">
              <div
                ref="networkContainer"
                style="width: 100%; height: 600px"
              ></div>
            </el-card>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-row>
  </div>
</template>

<script>
import http from '../utils/request'
import { mapMutations } from 'vuex';

import { DataSet, Network } from 'vis'
import { mapGetters } from 'vuex'
export default {
  name: 'importance',
  data() {
    return {
      tableData: [],
      startFlag: false,
      completedFlag: false,
      tableLabel: { id: 'ID', name: '节点名称', importance: '重要性' },
      nodes: new DataSet([]), // vis.js 节点数据
      edges: new DataSet([]), // vis.js 连接数据
      network: null, // vis.js 网络实例
    }
  },
  computed: {
    ...mapGetters({
      dataset: 'getDataset',
      AllNodes: 'getAllNodes',
      AllEdges: 'getAllEdges',
    }),
  },
  methods: {

    ...mapMutations(['setAllNodes', 'setAllEdges']),
    // 初始化网络图
    initNetwork() {
      const container = this.$refs.networkContainer
      this.network = new Network(
        container,
        { nodes: this.nodes, edges: this.edges },
        { physics: true }
      )
    },
    start() {
  this.startFlag = true;
  this.completedFlag = false;

  // request({
  //   url: ``,
  //   method: 'get',
  // })
      http.get('/importancemeasure/importance').then((res) => {
    console.log('res', res);
    this.completedFlag = true;
    this.startFlag = false;
    
    // 1. 处理数据格式,与文件infected_nodes.csv的列名保持一致
    const list = res.data.map(item => ({
      id: item.ID, // 或者使用 item.id 如果后端返回了ID
      nodeName: item.NodeName, // 或 item.name
      importance: item.Importance // 或 item.importance
    }));
    
    // 2. 更新Vuex状态
    this.$store.commit('changeAllNodes', list);
    
    // 3. 直接更新本地表格数据
    this.tableData = list.map(item => ({
      id: item.id,
      name: item.nodeName,
      importance: item.importance
    }));
    
    // 4. 更新可视化
    // this.updateVisualization();
  })
  .catch((err) => {
    console.error('请求失败：', err);
    this.startFlag = false;
    this.$message.error('请求失败');
  });

  // 保留超时处理
  setTimeout(() => {
    if (this.startFlag) {
      console.warn('请求超时');
      this.startFlag = false;
      this.updateVisualization();
    }
  }, 120000);
},
    // 可视化更新
    updateVisualization() {
      this.nodes.clear()
      this.edges.clear()
      this.tableData = []
      this.AllNodes.forEach((item) => {
        this.nodes.add({
          id: item.id,
          label: item.nodeName,
          color: this.getInterpolatedColor(item.importance),
          font: { color: 'white' },
        })
        this.tableData.push({
          id: item.id,
          name: item.nodeName,
          importance: item.importance,
        })
      })
      this.AllEdges.forEach((item) => {
        this.edges.add({ from: item.from, to: item.to })
      })
      this.initNetwork()
    },
    // 重要性颜色映射
    getInterpolatedColor(value) {
      const startColor = { r: 0, g: 0, b: 255 }
      const endColor = { r: 255, g: 0, b: 0 }
      const ratio = Math.max(0, Math.min(value, 1))
      const r = Math.round(startColor.r + (endColor.r - startColor.r) * ratio)
      const g = Math.round(startColor.g + (endColor.g - startColor.g) * ratio)
      const b = Math.round(startColor.b + (endColor.b - startColor.b) * ratio)
      return `#${[r, g, b]
        .map((x) => x.toString(16).padStart(2, '0'))
        .join('')}`
    },
  },
  mounted() {
    this.initNetwork()
  },
}
</script>

<style lang="less" scoped>
.tips {
  font-size: 20px;
}
.btn {
  width: 60%;
  margin-left: 20px;
  display: flex;
  justify-content: space-around;
}
</style>
